import gold from "../../../../imgs/gold.png";
import product from "../../../../imgs/product-1.jpg";
import dange from "../../../../imgs/dange.png";
import Input from "@ui/RJMart/input";
// import Textarea from '@ui/RJMart/textarea'
import Select, { Option } from "@ui/RJMart/select";
import HttpUtils from "../../common/utils/HttpUtils";
import EventEmitterUtils from "../../common/utils/EventEmitterUtils";
import ImageWithError from "@page/common/comps/ImageWithError";
import Rest from "@module/Rest";
import Icon from "@ui/RJMart/icons";
import Uts from "@module/Uts";
import ZenUI from "@root/components/ZenUI/ZenUI";
import ZDControls from "./../components/ZDControls";
//购物车所有商品列表
export default class ProductList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    getRemark(suppId, remark) {
        this.props.setRemarks(suppId, remark);
    }

    render() {
        return (
            <div className={"statement-prolist-wrapper"}>
                <div className={"statement-prolist"}>
                    <div className={"statement-prolist-top"}>
                        <p className={"statement-prolist-top-line"} />
                        <p className={"statement-prolist-top-title"}>
                            采购商品清单
                        </p>
                    </div>
                    <div className={"statement-prolist-table"}>
                        <div className={"statement-prolist-table-header"}>
                            <p className={"statement-prolist-table-header-p1"}>
                                商品
                            </p>
                            <p className={"statement-prolist-table-header-p2"}>
                                货号
                            </p>
                            <p className={"statement-prolist-table-header-p3"}>
                                规格
                            </p>
                            <p className={"statement-prolist-table-header-p4"}>
                                单价
                            </p>
                            <p className={"statement-prolist-table-header-p5"}>
                                数量
                            </p>
                            <p className={"statement-prolist-table-header-p6"}>
                                金额
                            </p>
                        </div>
                        {this.renderDetail()}
                    </div>
                </div>
            </div>
        );
    }

    renderDetail() {
        const {
            cartInfo,
            isGroupbuying,
            supplierName,
            productCount,
            categoryList
        } = this.props;
        if (isGroupbuying) {
            return (
                <React.Fragment>
                    {cartInfo &&
                        cartInfo.map((item, index) => (
                            <ProItemForGroup
                                item={item}
                                key={index}
                                index={index}
                                productCount={productCount}
                                supplierName={supplierName}
                                setItemRemark={(suppId, remark) =>
                                    this.getRemark(suppId, remark)
                                }
                            />
                        ))}
                </React.Fragment>
            );
        } else {
            return (
                <React.Fragment>
                    {cartInfo &&
                        cartInfo.map((item, index) => (
                            <ProductItem
                                item={item}
                                key={index}
                                index={index}
                                setItemRemark={(suppId, remark) =>
                                    this.getRemark(suppId, remark)
                                }
                                categoryList={categoryList}
                            />
                        ))}
                </React.Fragment>
            );
        }
    }
}

// carryFee: 0
// groupBuyingId: "2dc3b3e1-8b16-4fae-a434-25e7ce152dd7"
// id: 200000229443
// name: "半胱胺"
// number: "30070-10G"
// price: "1318"
// showPrice: "1280.00"
// specification: "10G"
// staircasePriceModels: Array(3)
// 0: {level: 1, minAmount: 0, maxAmount: 3, price: 1280, minLevel: true, …}
// 1: {level: 2, minAmount: 3, maxAmount: 5, price: 1200, minLevel: false, …}
// 2: {level: 3, minAmount: 5, maxAmount: 0, price: 1150, minLevel: false, …}
// length: 3
// __proto__: Array(0)
// suppId: 5
// url: "http://www.sigmaaldrich.com/content/dam/sigma-aldrich/structure0/184/mfcd00008196.eps/_jcr_content/renditions/mfcd00008196-large.png"

//单个供应商商品列表
class ProItemForGroup extends React.Component {
    getItemRemarkParams(remark, suppId) {
        this.props.setItemRemark(suppId, remark);
    }

    render() {
        const { item, index, free, supplierName, productCount } = this.props;
        // console.log("ProItemForGroup", item);
        const { name, carryFee, suppId } = item;

        return (
            <div>
                <div className={"statement-proitem-comp"}>
                    {/*<img src={gold} alt="" />*/}
                    <p dangerouslySetInnerHTML={{ __html: supplierName }} />
                </div>
                <div className={"statement-pro-info-wrapper"}>
                    <ProductInfoGroup
                        key={`${index}-group`}
                        item={item}
                        productCount={productCount}
                        classMark={`statement-pro-info-boxcontent-${index}`}
                    />
                    <LeaveMsgGroup
                        totalCarryFee={carryFee}
                        cupons={[]}
                        classMark={`statement-pro-info-boxcontent-${index}`}
                        setMsg={remark => {
                            this.getItemRemarkParams(remark, suppId);
                        }}
                    />
                </div>
            </div>
        );
    }
}

//单个商品
class ProductItem extends React.Component {
    constructor() {
        super();
        this.state = {
            cupons: []
        };
    }

    getItemRemarkParams(remark, supplier) {
        let suppId = supplier.id;
        this.props.setItemRemark(suppId, remark);
    }

    getCartIds(cart) {
        let cart_ = JSON.parse(JSON.stringify(cart));
        let ids = [];
        if (cart_ && cart_.length > 0) {
            cart_.forEach(item => {
                ids.push(item.id);
            });
        }
        return ids;
    }

    componentDidMount() {
        this.getCouponForPurchaser();
    }

    getCouponForPurchaser() {
        const { item, index } = this.props;
        const { cart, supplier } = item;
        const cartIds = this.getCartIds(cart);
        const suppId = supplier.id;

        let url = `/store/api/coupon/getCouponForPurchaser`;
        let params = {
            cartIds: cartIds,
            suppId: suppId + ""
        };

        Rest.post(url, params)
            .then(res => {
                console.log(res);
                if (res.message == "success") {
                    let tmplCupons = res.cupons.filter((v, i) => {
                        return v.state != "20";
                    });
                    this.setState({
                        cupons: tmplCupons
                    });
                }
            })
            .catch(err => {
                console.log(err);
            });
    }

    render() {
        const { item, index, free } = this.props;
        const { cart, supplier } = item;
        let totalProductAmountForOneSupplier = Uts.countTotalFromArray(
            cart,
            "countPrice"
        );
        let totalProductCountForOneSupplier = cart.length;
        // console.log(item, totalProductAmountForOneSupplier);
        const { name } = supplier;
        const { cupons } = this.state;
        return (
            <div>
                <div className={"statement-proitem-comp"}>
                    {/*<img src={gold} alt="" />*/}
                    <p dangerouslySetInnerHTML={{ __html: name }} />
                </div>
                <div className={"statement-pro-info-wrapper"}>
                    {cart.map((item, idx) => (
                        <ProductInfo
                            key={`${index}-${idx}`}
                            item={item}
                            classMark={`statement-pro-info-boxcontent-${index}`}
                            categoryList={this.props.categoryList}
                        />
                    ))}
                    <LeaveMsg
                        totalCarryFee={item.totalCarryFee}
                        totalProductAmountForOneSupplier={
                            totalProductAmountForOneSupplier
                        }
                        totalProductCountForOneSupplier={
                            totalProductCountForOneSupplier
                        }
                        cupons={cupons}
                        classMark={`statement-pro-info-boxcontent-${index}`}
                        setMsg={remark => {
                            this.getItemRemarkParams(remark, supplier);
                        }}
                    />
                </div>
            </div>
        );
    }
}

//单个供应商商品列表（不包含显示统计费用）
class ProductInfoGroup extends React.Component {
    render() {
        const { item, classMark, productCount } = this.props;
        // console.log("ProductInfoGroup", item);
        const {
            url,
            carryFee,
            name,
            number,
            price,
            showPrice,
            specification,
            staircasePriceModels,
            suppId,
            dangerousTag
        } = item;

        // staircasePriceModels: [{level: 1, minAmount: 0, maxAmount: 2, price: 400, minLevel: true, maxLevel: false},…]
        // 0: {level: 1, minAmount: 0, maxAmount: 2, price: 400, minLevel: true, maxLevel: false}
        // 1: {level: 2, minAmount: 2, maxAmount: 5, price: 300, minLevel: false, maxLevel: false}
        // 2: {level: 3, minAmount: 5, maxAmount: 0, price: 200, minLevel: false, maxLevel: true}
        // // suppId: 644
        // let groupPrice = this.getGroupPrice(staircasePriceModels, productCount);
        let groupPrice = showPrice;
        return (
            <div className={`${classMark} statement-pro-info`}>
                <div className={"statement-pro-info-p1"}>
                    <ImageWithError
                        className={"statement-pro-info-img"}
                        src={url}
                    />
                    <div className={"statement-pro-info-name-box"}>
                        <p className={"statement-pro-info-name"}>{name}</p>
                        {dangerousTag &&
                            dangerousTag != "其他" &&
                            dangerousTag != "常规化学品" && (
                                <div className={"statement-pro-info-dange"}>
                                    <img src={dange} alt="" />
                                    <p>{dangerousTag}</p>
                                </div>
                            )}
                    </div>
                </div>
                <p className={"statement-pro-info-p2"}>{number}</p>
                <p className={"statement-pro-info-p3"}>
                    {" "}
                    {Filter.cutString(specification, 40, 1)}
                </p>
                <p className={"statement-pro-info-p4"}>
                    {`￥${Filter.float(groupPrice, 2)}`}
                </p>
                <p className={"statement-pro-info-p5"}>{productCount}</p>
                <p className={"statement-pro-info-p6"}>
                    {`￥${Filter.float(
                        (groupPrice - 0) * (productCount - 0),
                        2
                    )}`}
                </p>
            </div>
        );
    }

    getGroupPrice(staircasePriceModels, productCount) {
        let price = 0;

        for (let i = 0; i < staircasePriceModels.length; i++) {
            let item = staircasePriceModels[i];
            if (item.maxLevel) {
                if (productCount > item.minAmount) {
                    price = item.price;
                    break;
                }
            } else {
                if (
                    productCount > item.minAmount &&
                    productCount <= item.maxAmount
                ) {
                    price = item.price;
                    break;
                }
            }
        }

        return price;
    }
}

class ProductInfo extends React.Component {
    render() {
        const { item, classMark } = this.props;
        const { product, amount, countPrice } = item;
        const {
            name,
            productNum,
            photo,
            sku,
            price,
            unifyPrice,
            brandName,
            brandId,
            dangerousTag,
            specification,
            hasActivity,
            sn,
            categoryDirectoryId,
            casNo
        } = product;
        return (
            <div>
                <div className={Uts.sc([classMark,'statement-pro-info',!(Uts.getCookie("orgId")=='3'&&!casNo&&this.props.categoryList)?'zen_bdb-D1D1D1':''])}>
                    <div className={"statement-pro-info-p1"}>
                        <ImageWithError
                            className={"statement-pro-info-img"}
                            src={photo}
                        />
                        <div className={"statement-pro-info-name-box"}>
                            <p className={"statement-pro-info-name"}>{name}</p>
                            {dangerousTag &&
                                dangerousTag != "其他" &&
                                dangerousTag != "常规化学品" && (
                                    <div className={"statement-pro-info-dange"}>
                                        <img src={dange} alt="" />
                                        <p>{dangerousTag}</p>
                                    </div>
                                )}
                        </div>
                    </div>
                    <p className={"statement-pro-info-p2"}>{productNum}</p>
                    <p className={"statement-pro-info-p3"}>
                        {Filter.cutString(specification, 40, 1)}
                    </p>
                    <div className={"statement-pro-info-p4"}>
                        {`￥${price.toFixed(2)}`}
                        {hasActivity && (
                            <div>
                                <p
                                    className={
                                        "cart-pro-item-content-unifyPrice"
                                    }
                                >
                                    {" "}
                                    {`￥${unifyPrice.toFixed(2)}`}
                                </p>
                            </div>
                        )}
                    </div>
                    <p className={"statement-pro-info-p5"}>{amount}</p>
                    <p className={"statement-pro-info-p6"}>
                        {`￥${countPrice.toFixed(2)}`}
                    </p>
                </div>
                {
                    Uts.getCookie("orgId")=='3'&&!casNo&&this.props.categoryList&&<ZDControls categoryList={this.props.categoryList} sn={sn} defaultId={categoryDirectoryId} />
                }
                
            </div>
        );
    }

    getTotalPrice(unifyPrice, amount) {
        let totalPrice = (unifyPrice - 0) * amount;
        return `￥${totalPrice.toFixed(2)}`;
    }
}

//显示统计费用
class LeaveMsgGroup extends React.Component {
    constructor(props) {
        super(props);
        const { cupons } = this.props;
        this.defaultCupons = cupons[0] || {};
        let { couponNumber } = this.defaultCupons;
        this.state = {
            totalPrice: 0,
            msg: "",
            couponNumber: couponNumber ? couponNumber - 0 : 0
        };
    }

    componentDidMount() {
        this.getPrice();
    }

    getPrice() {
        const { classMark } = this.props;
        const eleList = document.querySelectorAll(
            `.${classMark} .statement-pro-info-p6`
        );

        let totalPrice = 0;
        if (eleList) {
            eleList.forEach(ele => {
                let price = ele.innerHTML.split("￥")[1] - 0;
                totalPrice += price;
            });
            this.setState(
                {
                    totalPrice: totalPrice - 0
                }
                // this.emitCounPrice
            );
        }
    }

    // emitCounPrice() {
    //     let totalCouponPrice = this.getTotalCouponsNumber();
    //     let cuponRefIds = this.getCuponRefIds();
    //     console.log(totalCouponPrice);
    //     console.log(cuponRefIds);
    //     let params = {
    //         totalCouponPrice,
    //         cuponRefIds
    //     };
    //     let paramsStr = Uts.toStr(params);
    //     EventEmitterUtils.emit("getTotalCouponsInfo", paramsStr);
    // }

    render() {
        const { totalPrice, msg, couponNumber } = this.state;
        const { cupons, classMark, totalCarryFee } = this.props;
        return (
            <div className={`${classMark} statement-pro-msg`}>
                <div className={"statement-pro-msg-txt"}>
                    <p>买家留言</p>
                    <Input
                        className={"statement-pro-msg-input"}
                        value={msg}
                        onChange={e => {
                            let msg = e.target.value;
                            this.setState(
                                {
                                    msg: msg
                                },
                                () => this.props.setMsg(msg)
                            );
                        }}
                    />
                </div>

                {/*<div className={"statement-pro-msg-price-jian"}>*/}
                {/*<p*/}
                {/*couponnumber={couponNumber}*/}
                {/*className={"statement-pro-msg-price-jian-p"}*/}
                {/*>*/}
                {/*-¥{couponNumber.toFixed(2)}*/}
                {/*</p>*/}
                {/*</div>*/}
                <div className={"statement-pro-msg-price-group"}>
                    <p className={"statement-pro-msg-price-p1"}>合计：</p>
                    <p className={"statement-pro-msg-price-p2"}>
                        {totalPrice.toFixed(2)}
                    </p>
                    <span className="zen_fs-14">
                        {`(含运费￥${totalCarryFee})`}
                    </span>
                </div>
            </div>
        );
    }
}

class LeaveMsg extends React.Component {
    constructor(props) {
        super(props);
        const { cupons } = this.props;
        this.defaultCupons = cupons[0] || {};
        let isValid = this.checkCounpsIfValid(this.defaultCupons, 1);
        let { couponNumber } = this.defaultCupons;
        this.state = {
            totalPrice: 0,
            msg: "",
            couponNumber: isValid ? (couponNumber ? couponNumber - 0 : 0) : 0
        };
    }

    componentDidMount() {
        let isFrist = true;
        this.getPrice(isFrist);
    }

    checkCounpsIfValid(CounpsItem, isNoNoti) {
        let isValid = false;
        //至少xxx金额
        if (CounpsItem.buyerPurchase == 20) {
            if (
                this.props.totalProductAmountForOneSupplier >
                CounpsItem.buyerPurchasesNumber
            ) {
                isValid = true;
            }
        }
        //至少xxx件商品
        else if (CounpsItem.buyerPurchase == 10) {
            if (
                this.props.totalProductCountForOneSupplier >
                CounpsItem.buyerPurchasesNumber
            ) {
                isValid = true;
            }
        }

        if (!isValid && !isNoNoti) {
            ZenUI.ST("您好，当前所选优惠卷不满足使用要求，请重新核对选择", 3);
        }

        return isValid;
    }

    componentWillReceiveProps(nextProps) {
        let oldLength = this.props.cupons.length;
        let len = nextProps.cupons.length;
        if (len > 0 && oldLength != len) {
            let { couponNumber } = nextProps.cupons[0] || {};
            let isValid = this.checkCounpsIfValid(nextProps.cupons[0], 1);
            this.setState(
                {
                    couponNumber: isValid
                        ? couponNumber
                            ? couponNumber - 0
                            : 0
                        : 0
                },
                this.getPrice
            );
        }
    }

    getPrice(isFrist) {
        const { classMark } = this.props;
        const eleList = document.querySelectorAll(
            `.${classMark} .statement-pro-info-p6`
        );
        const couponEle = document.querySelector(
            `.${classMark} .statement-pro-msg-price-jian-p`
        );
        const couponNumber = couponEle.getAttribute("couponnumber");
        let totalPrice = 0;
        if (eleList) {
            // eleList.forEach(ele => {
            //     let price = ele.innerHTML.split("￥")[1] - 0;
            //     totalPrice += price;
            // });
            this.setState(
                {
                    totalPrice:
                        this.props.totalProductAmountForOneSupplier -
                        (couponNumber - 0)
                },
                this.emitCounPrice(isFrist)
            );
        }
    }

    emitCounPrice(isFrist) {
        let totalCouponPrice = this.getTotalCouponsNumber();
        let cuponRefIds = this.getCuponRefIds();

        let params = {
            totalCouponPrice,
            cuponRefIds,
            isFrist: isFrist
        };
        let paramsStr = Uts.toStr(params);

        EventEmitterUtils.emit("getTotalCouponsInfo", paramsStr);
    }

    getCuponRefIds() {
        const eleList = document.querySelectorAll(".statements-counps-input");
        let cuponRefIds = [];
        if (eleList) {
            eleList.forEach(ele => {
                let cuponRefId = ele.getAttribute("cuponrefid");
                if (cuponRefId != null) {
                    cuponRefIds.push(cuponRefId);
                }
            });
        }
        return cuponRefIds;
    }

    getTotalCouponsNumber() {
        const eleList = document.querySelectorAll(
            ".statement-pro-msg-price-jian-p"
        );
        let totalCouponPrice = 0;
        if (eleList) {
            eleList.forEach(ele => {
                let couponNumber = ele.getAttribute("couponnumber");
                totalCouponPrice += couponNumber - 0;
            });
        }
        return totalCouponPrice;
    }

    render() {
        const { totalPrice, msg, couponNumber } = this.state;
        const { cupons, classMark, totalCarryFee } = this.props;
        return (
            <div className={`${classMark} statement-pro-msg`}>
                <div className={"statement-pro-msg-txt"}>
                    <p>买家留言</p>
                    <Input
                        className={"statement-pro-msg-input"}
                        value={msg}
                        onChange={e => {
                            let msg = e.target.value;
                            this.setState(
                                {
                                    msg: msg
                                },
                                () => this.props.setMsg(msg)
                            );
                        }}
                    />
                </div>
                <div className={"statement-pro-msg-youhui"}>
                    <p>商家优惠</p>
                    {cupons && cupons.length > 0 ? (
                        <SelectCounps
                            cupons={cupons}
                            totalProductAmountForOneSupplier={
                                this.props.totalProductAmountForOneSupplier
                            }
                            totalProductCountForOneSupplier={
                                this.props.totalProductCountForOneSupplier
                            }
                            setCounpNumber={couponNumber => {
                                this.setState(
                                    {
                                        couponNumber: couponNumber
                                    },
                                    this.getPrice
                                );
                            }}
                        />
                    ) : (
                        <div className={"statement-pro-msg-youhui-no"}>
                            <p>无优惠</p>
                        </div>
                    )}
                </div>
                <div className={"statement-pro-msg-price-jian"}>
                    <p
                        couponnumber={couponNumber}
                        className={"statement-pro-msg-price-jian-p"}
                    >
                        -¥{couponNumber.toFixed(2)}
                    </p>
                </div>
                <div className={"statement-pro-msg-price"}>
                    <p className={"statement-pro-msg-price-p1"}>合计：</p>
                    <p className={"statement-pro-msg-price-p2"}>
                        {(
                            this.props.totalProductAmountForOneSupplier -
                            couponNumber
                        ).toFixed(2)}
                    </p>
                    <span className="zen_fs-14">
                        {`(含运费￥${totalCarryFee})`}
                    </span>
                </div>
            </div>
        );
    }
}

class SelectCounps extends React.Component {
    constructor(props) {
        super(props);
        const { cupons } = this.props;
        this.defaultCupons = cupons[0];
        let {
            buyerPurchase,
            buyerPurchasesNumber,
            couponId,
            couponNumber,
            refId
        } = this.defaultCupons;

        this.state = {
            value: this.checkCounpsIfValid(cupons[0], 1)
                ? `${couponNumber}现金券：满${buyerPurchasesNumber}可用`
                : `请选择`,
            showOpt: false,
            cuponRefId: this.checkCounpsIfValid(cupons[0], 1) ? refId : null
        };
    }

    checkCounpsIfValid(CounpsItem, isNoNoti) {
        let isValid = false;
        //至少xxx金额
        if (CounpsItem.buyerPurchase == 20) {
            if (
                this.props.totalProductAmountForOneSupplier >=
                CounpsItem.buyerPurchasesNumber
            ) {
                isValid = true;
            }
        }
        //至少xxx件商品
        else if (CounpsItem.buyerPurchase == 10) {
            if (
                this.props.totalProductCountForOneSupplier >=
                CounpsItem.buyerPurchasesNumber
            ) {
                isValid = true;
            }
        }

        if (!isValid && !isNoNoti) {
            ZenUI.ST("您好，当前所选优惠卷不满足使用要求，请重新核对选择", 3);
        }

        return isValid;
    }

    // buyerPurchase: 20
    // buyerPurchasesNumber: "200"
    // couponId: "1ce5c26a-47e2-442b-8a81-39159bc73ab8"
    // couponNumber: "20"
    // endDate: "2019-05-24"
    // range: 10
    // refId: "7b3c4d86-aecf-4c07-aec9-e01b638c2b56"
    // startDate: "2019-05-23"
    // state: 0
    // supplier: "宏兴生物信息科技有限公司"

    render() {
        const { value, showOpt, cuponRefId } = this.state;
        const { cupons } = this.props;
        return (
            <div className={"statements-counps-input-content"}>
                <div
                    cuponrefid={cuponRefId}
                    onClick={() => {
                        this.setState({
                            showOpt: true
                        });
                    }}
                    className={"statements-counps-input"}
                >
                    <p>{value}</p>
                    <div className={"statements-counps-icons-box"}>
                        <Icon type={"down"} width={15} />
                    </div>
                </div>

                {showOpt && (
                    <div className={"statements-counps-options"}>
                        {cupons &&
                            cupons.map((item, index) => {
                                let {
                                    couponNumber,
                                    buyerPurchasesNumber,
                                    refId
                                } = item;
                                let value = `${couponNumber}现金券：满${buyerPurchasesNumber}可用`;
                                return (
                                    <div
                                        onClick={() => {
                                            if (this.checkCounpsIfValid(item)) {
                                                this.setState(
                                                    {
                                                        showOpt: false,
                                                        value: value,
                                                        cuponRefId: refId
                                                    },
                                                    () =>
                                                        this.props.setCounpNumber(
                                                            couponNumber - 0
                                                        )
                                                );
                                            }
                                        }}
                                        key={index}
                                        className={"statements-counps-item"}
                                    >
                                        <p>{value}</p>
                                    </div>
                                );
                            })}
                        {
                            <div
                                onClick={() => {
                                    this.setState(
                                        {
                                            showOpt: false,
                                            value: `不使用优惠券`,
                                            cuponRefId: null
                                        },
                                        () => this.props.setCounpNumber(0)
                                    );
                                }}
                                className={"statements-counps-item"}
                            >
                                <p>{"不使用优惠券"}</p>
                            </div>
                        }
                    </div>
                )}
            </div>
        );
    }
}
